//
//  AudioViewController.m
//  test
//
//  Created by mac on 2017/8/30.
//  Copyright © 2017年 mac. All rights reserved.
//

#import "AudioViewController.h"
#import <Speech/Speech.h>


@interface AudioViewController ()<SFSpeechRecognizerDelegate>

@property (nonatomic, strong) SFSpeechRecognizer *speechRecognizer;

@property (nonatomic, strong) SFSpeechRecognitionTask *recognitionTask;

@property (nonatomic, strong) SFSpeechAudioBufferRecognitionRequest *recognitionRequest;

/// 音频引擎
@property (nonatomic, strong) AVAudioEngine *audioEngine;


@end
UILabel *label;
UIButton *btn;
@implementation AudioViewController


- (void)dealloc {
    [self.recognitionTask cancel];
    self.recognitionTask = nil;
}


- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor =[UIColor whiteColor];
    label = [[UILabel alloc]initWithFrame:CGRectMake(0,50,self.view.frame.size.width,200)];
    label.text= @"Hello world!";
    label.textColor = [UIColor orangeColor];
    label.font=[UIFont
    fontWithName:@"Arial-BoldItalicMT"
    size:32];
    [label setTextAlignment:NSTextAlignmentCenter];
    label.shadowColor = [UIColor blackColor];
    [self.view addSubview:label];
    // 按钮
    btn = [UIButton buttonWithType:UIButtonTypeRoundedRect];
    CGRect frame;
    frame.size.width = 150;
    frame.size.height = 40;
    frame.origin.x = self.view.frame.size.width / 2 - 75;
    frame.origin.y = self.view.frame.size.height / 2 + 150;
    [btn setFrame:frame];
    [btn setTitle:@"录音" forState:UIControlStateNormal];
    [btn addTarget:self action:@selector(btnPressed) forControlEvents:UIControlEventTouchUpInside];
    [btn setBackgroundColor:[UIColor orangeColor]];
    [btn setAlpha:0.8];
    btn.layer.cornerRadius=5;
    [btn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [self.view addSubview:btn];
    
  
    /// 创建语音识别器对象并设置代理
    self.speechRecognizer = [[SFSpeechRecognizer alloc] init];
    self.speechRecognizer.delegate = self;
 
    /// 请求用户授权
    [SFSpeechRecognizer requestAuthorization:^(SFSpeechRecognizerAuthorizationStatus status) {
        BOOL isButtonEnabled = NO;
        switch (status) {
            case SFSpeechRecognizerAuthorizationStatusNotDetermined:
                isButtonEnabled = NO;
                NSLog(@"SFSpeechRecognizerAuthorizationStatusNotDetermined");
                break;
            case SFSpeechRecognizerAuthorizationStatusDenied:
                isButtonEnabled = NO;
                NSLog(@"SFSpeechRecognizerAuthorizationStatusDenied");
                break;
            case SFSpeechRecognizerAuthorizationStatusRestricted:
                isButtonEnabled = NO;
                NSLog(@"SFSpeechRecognizerAuthorizationStatusRestricted");
                break;
            case SFSpeechRecognizerAuthorizationStatusAuthorized:
                NSLog(@"SFSpeechRecognizerAuthorizationStatusAuthorized");
                isButtonEnabled = YES;
                break;
            default:
                break;
        }
        dispatch_async(dispatch_get_main_queue(), ^{
            btn.enabled = isButtonEnabled;
        });
    }];
    /// 创建音频引擎对象
    self.audioEngine = [[AVAudioEngine alloc] init];
}


#pragma mark - private method
- (void)startRecording {
    if (self.recognitionTask != nil) {
        [self.recognitionTask cancel]; // 取消当前语音识别任务
        self.recognitionTask = nil;
    }
    
    AVAudioSession *audioSession = [AVAudioSession sharedInstance];
    NSError *categoryError = nil;
    if (![audioSession setCategory:AVAudioSessionCategoryRecord error:&categoryError]) {
        NSLog(@"categoryError: %@", categoryError.localizedDescription);
    }
    
    NSError *modeError = nil;
    if (![audioSession setMode:AVAudioSessionModeMeasurement error:&modeError]) {
        NSLog(@"modeError: %@", modeError.localizedDescription);
    }
    
    NSError *activeError = nil;
    if (![audioSession setActive:YES withOptions:AVAudioSessionSetActiveOptionNotifyOthersOnDeactivation error:&activeError]) {
        NSLog(@"activeError: %@", activeError.localizedDescription);
    }
    
    /// 实例化 通过设备麦克风识别现场语音的请求 对象
    self.recognitionRequest = [[SFSpeechAudioBufferRecognitionRequest alloc] init];
    
    if (!self.audioEngine.inputNode) {// 系统输入节点
        NSLog(@"Audio engine has no input node");
        return;
    }
    
    if (!self.recognitionRequest) {
        NSLog(@"Unable to create an SFSpeechAudioBufferRecongitionRequest object");
        return;
    }
    
    /// 报告每个发音的部分非精确结果
    self.recognitionRequest.shouldReportPartialResults = YES;
    
    /// 执行语音识别任务 完成回调
    self.recognitionTask = [self.speechRecognizer recognitionTaskWithRequest:self.recognitionRequest resultHandler:^(SFSpeechRecognitionResult * _Nullable result, NSError * _Nullable error) {
        
        BOOL isFinal = NO;
        
        if (result) {
            label.text = result.bestTranscription.formattedString;
            isFinal = result.isFinal;
        }
        
        if (error || isFinal) {
            [self.audioEngine stop];
            [self.audioEngine.inputNode removeTapOnBus:0];
            
            self.recognitionRequest = nil;
            self.recognitionTask = nil;
            
            btn.enabled = YES;
        }
    }];
    
    AVAudioFormat *recordingFormat = [self.audioEngine.inputNode outputFormatForBus:0];
    
    [self.audioEngine.inputNode installTapOnBus:0 bufferSize:1024 format:recordingFormat block:^(AVAudioPCMBuffer * _Nonnull buffer, AVAudioTime * _Nonnull when) {
        /// 将PCM格式的音频追加到识别请求的结尾
        [self.recognitionRequest appendAudioPCMBuffer:buffer];
    }];
    
    [self.audioEngine prepare];
    
    NSError *startError = nil;
    if(![self.audioEngine startAndReturnError:&startError]) {
        NSLog(@"startError: %@", startError.localizedDescription);
    }
    
    label.text = @"Say something, I'm listening";
}

#pragma mark - SFSpeechRecognizerDelegate
- (void)speechRecognizer:(SFSpeechRecognizer *)speechRecognizer availabilityDidChange:(BOOL)available {
    if (available) {
        btn.enabled = YES;
    } else {
        btn.enabled = NO;
    }
}





-(void)btnPressed{
   
    if (self.audioEngine.isRunning) {
        [self.audioEngine stop];
        [self.recognitionRequest endAudio];
        btn.enabled = NO;
        [btn setTitle:@"Start Recording" forState:UIControlStateNormal];
    } else {
        NSLog(@"===");
        [self startRecording];
        [btn setTitle:@"Stop Recording" forState:UIControlStateNormal];
    }
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}



@end
